package com.cat.dynamicPlanning;

import java.util.Arrays;
import java.util.HashSet;

/**
 *   @description https://leetcode.cn/problems/partition-string-into-minimum-beautiful-substrings/
 *   @author 曲大人的喵
 *   @create 2025/9/5 15:20
 *   @since JDK17
 */

public class Solution76 {
    static HashSet<Integer> set = new HashSet<>();
    static {
        for (int i = 0; i < 9; i++) {
            set.add(((int) Math.pow(5, i)));
        }
    }


    int f(String nums) {
        if (nums.length() > 0 && nums.charAt(0) == '0') {
            return 0;
        }
        int ans = 0, n = nums.length();
        for (int i = 0; i < n; i++) {
            if (nums.charAt(i) != '0') {
                ans += Math.pow(2, n - i - 1);
            }
        }
        return ans;
    }

    public int minimumBeautifulSubstrings(String s) {
        int n = s.length();
        int[] dp = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) { // 用
                if (set.contains(f(s.substring(j, i))) && dp[j] != Integer.MAX_VALUE) {
                    dp[i] = Math.min(dp[i], (j == 0 ? 1 : dp[j] + 1));
                }
            }
            if (dp[i - 1] != Integer.MAX_VALUE && s.charAt(i - 1) != '0') {
                dp[i] = Math.min(dp[i - 1] + 1, dp[i]);
            }
        }
        return dp[n] == Integer.MAX_VALUE ? -1 : dp[n];
    }
}
